var common = require('../../../utils/common.js');
// pages/home/search/search.js
Page({
  data: {
    searchInput: true,
    inputFocus: false,
    loadHidden: true,
    hasMore: false,
    tipNone: true,
    inputKey: '',
    coaches: [],
    activities: []
  },
  skip: 0,
  take: 10,
  subTake:0,
  loadMore: false,
  searchFocus: function () {
    this.setData({
      searchInput: false,
      inputFocus: true,
    });
  },
  searchCancel: function () {
    this.setData({
      searchInput: true,
      inputFocus: false,
      inputKey: '',
      tipNone: true,
    });
  },
  searchInputKey: function (e) {
    let that = this;
    that.skip = 0; that.take = 10;
    that.loadMore = false;
    if (e.detail.value) {
      that.setData({
        coaches: [],
        activities: [],
        loadHidden: false,
        inputKey: e.detail.value
      });
      that.reqSearch(e.detail.value);
    }
  },
  reqSearch: function (key) {
    let that = this;
    common.asynPost(common.API.search.search, {
      skip: that.skip,
      take: that.take,
      key: key
    }, function (re) {
      that.setData({
        loadHidden: true
      });
      if (re['result'] && (re['result']['coach'].length || re['result']['activities'].length)) {
        if(re['result']['coach'].length > re['result']['activities'].length){
          that.subTake = (that.take - re['result']['coach'].length)
        }else{
           that.subTake = (that.take - re['result']['activities'].length)
        }
        that.loadMore = true;
        that.setData({
          coaches: that.data.coaches.concat(re['result']['coach']),
          activities: that.data.activities.concat(re['result']['activities']),
          tipNone: true,
        });
      } else {
        that.skip -= (that.take - that.subTake);
        that.setData({
          hasMore: true,
          tipNone: false,
        });
      }
    });
  },
  onReachBottom: function () {
    var that = this;
    if (that.loadMore) {
      that.setData({
        tipNone: false,
        hasMore: false
      });
      that.skip += (that.take - that.subTake);
      that.reqSearch(that.data.inputKey);
    }
  },
  nowBook: function (event) {
    var id = event.currentTarget.dataset.id;
    wx.navigateTo({ url: '../../coach/detail/detail?id=' + id });
  },
  handleActivity:function(e){
    let id = e.currentTarget.dataset.id, type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url:'../../activity/detail/detail?id=' + id
      });
    } else {
      wx.navigateTo({
        url:'../../activity/special/special?id=' + id
      });
    }
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})
